package org.utils.xml.xmlupdater;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;

import org.utils.common.InitException;
import org.utils.xml.XMLDataNode;

/**
 * @author  Manuel EVENO
 * @version 1.0
 */
public class DefinesHandler
{
  private static DefinesHandler instance = null;

  public static void init(XMLDataNode config)
  {
	  instance = new DefinesHandler(config);
  }

  public static DefinesHandler getInstance() throws InitException
  {
	  if (instance == null)
		throw new InitException("This handler must have been initialized before you can use it");
	  return instance;
  }

  private Hashtable constants = null;
  /**
   * Creates a new DefinesHandler
   */
  public DefinesHandler(XMLDataNode config)
  {
    constants = new Hashtable();
    if (config == null)
      return ;
//      throw new InitException("The configuration node named Defines couldn't be found in the configuration file");
    ArrayList childs = config.getChildren();
    for (int i = 0; i < childs.size(); i++)
    {
      XMLDataNode child = (XMLDataNode) childs.get(i);
      String name = child.getAttribute("name");
      String type = child.getAttribute("type");
      String value = child.getAttribute("value");
      if (type.equals("const"))
	constants.put(name, new Constant(name, value));
    }
  }

  public String parseValue(String value)
  {
    StringBuffer buffer = new StringBuffer();
    int pos = 0;
    int last = 0;
    while ( (pos = value.indexOf("${", last)) >= 0)
    {
      int end = value.indexOf("}", pos);
      String cname = value.substring(pos+2, end);
      buffer.append( value.substring(last, pos) );
      buffer.append( getValue(cname) );
      last = end+1;
    }
    buffer.append( value.substring(last) );
    return buffer.toString();
  }

  public String getValue(String name)
  {
    if (constants.containsKey(name))
    	return ((Constant) constants.get(name)).getValue();
    throw new NoSuchConstantException(name);
  }

  public String toString()
  {
    StringBuffer buffer = new StringBuffer();
    String newLine = System.getProperty("line.separator");
    buffer.append("Constants:"+newLine);
    Iterator iterator = constants.keySet().iterator();
    while (iterator.hasNext())
    {
      String item = (String) iterator.next();
      buffer/*.append( item.toString() ).append('=').*/.append(constants.get(item)).append(newLine);
    }
    return buffer.toString();
  }
}
// End of DefinesHandler.java
